package coroutines

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun CoroutineScope.produceNums() = produce<Int> {
    var x  =1
    while (true){
        send(x++)
        delay(100)
    }
}

fun CoroutineScope.launchProcessor(id : Int, channel : ReceiveChannel<Int>) = launch {
    for (msg in channel){
        println("Processor #$id, received $msg")
    }
}

fun main(){
    runBlocking {
        val channel = produceNums()
        repeat(5){
            launchProcessor(it, channel)
        }
        delay(950)
        channel.cancel()
    }
}